import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import React, { useState, useCallback, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';
import { Button, Collapse, Input, Icon, InputNumber, message, Select, Modal } from 'antd';
import styles from './index.less';
import moment from 'moment';

import {
  getPkgDetailInfo
} from '../service';
import {
  Const
} from '../../Const';

import CTSelect from './CTSelect';

const { Panel } = Collapse;
const FormItem = Form.Item;
const { Option } = Select;

import PicUpload from './PicUpload';
import ShowPic from './ShowPic';

// 单个旅客信息
const PassengerInfoItem = props => {
  const { item, index, changeIsTravelInfo, deletePassengerInfo, changeIsSave, form, passengerInfo } = props;

  const pkgNoValidator = useCallback((rule, value, callback, index) => {
    let pkgDetailInfoDtoList = form.getFieldValue('pkgDetailInfoDtoList') || [];
    let arr = [];
    pkgDetailInfoDtoList.forEach((item, indexNum) => {
      if (index !== indexNum) arr.push(item.pkgNo)
    })
    if (arr.indexOf(value) > -1) {
      callback('行李牌号重复');
    } else {
      callback();
    }
  }, [passengerInfo, form]);

  return (
    <div className={styles.passengerInfoItemContent}>
      <div>
        <FormItem {...Const.formLayoutThree} label="行李牌号：">
          {form.getFieldDecorator(`pkgDetailInfoDtoList[${index}].pkgNo`, {
            rules: [
              { required: true, message: '请输入行李牌号' },
              { pattern: /^([A-Z\d]{6}|[A-Z\d]{8}|[A-Z\d]{10})$/, message: '行李牌号不正确，正确格式如123456、AA123456、1234567890' },
              { validator: (rule, value, callback) => pkgNoValidator(rule, value, callback, index) }
            ],
            initialValue: ''
          })(
            <Input disabled={item.isSave} placeholder="请输入" maxLength={10} />
          )}
        </FormItem>
      </div>
      <div>
        <FormItem {...Const.formLayoutThree} label="行李航线：">
          {form.getFieldDecorator(`pkgDetailInfoDtoList[${index}].pkgSegment`, {
            rules: [
              { required: true, message: '请输入行李航线' },
              { pattern: /^[A-Z]{3}-([A-Z]{3}-)?[A-Z]{3}$/, message: '请输入正确格式' },
            ],
            initialValue: ''
          })(
            <Input
              disabled={item.isSave}
              onBlur={e => {
                let val = e.target.value;
                if (val) {
                  val = val.toUpperCase();
                  if (/^[A-Z]{3}-([A-Z]{3}-)?[A-Z]{3}$/.test(val)) {
                    let _pkgDetailInfoDtoList = form.getFieldValue('pkgDetailInfoDtoList') || [];
                    _pkgDetailInfoDtoList[index]['pkgSegment'] = val;
                    let arr = val.split('-');
                    if (arr.length >= 2 && arr[1]) {
                      _pkgDetailInfoDtoList[index]['pkgDst'] = arr[arr.length - 1];
                    }
                    setTimeout(() => {
                      form.setFieldsValue({
                        pkgDetailInfoDtoList: _pkgDetailInfoDtoList
                      });
                    }, 0)
                  }
                }
              }}
              placeholder="请输入" />
          )}
        </FormItem>
      </div>
      <div>
        <FormItem {...Const.formLayoutThree} label="行李牌上目的地：">
          {form.getFieldDecorator(`pkgDetailInfoDtoList[${index}].pkgDst`, {
            rules: [
              { required: true, message: '请输入行李牌上目的地' }
            ],
            initialValue: ''
          })(
            <Input disabled placeholder="请输入" />
          )}
        </FormItem>
      </div>
      <div style={{ justifyContent: 'flex-end' }}>
        <div style={{ width: 'auto' }}>
          {item.isSave ? (item.isTravelInfo ? <>
            <Button
              disabled
              type="link">
              已添加
            </Button>
            <span>|</span>
            <Button
              type="link"
              onClick={() => changeIsTravelInfo(index)}>
              取消
            </Button>
          </> : (item.isRelation ? <Button
            type="link"
            onClick={() => changeIsTravelInfo(index)}>
            查看
          </Button> : (<>
            <Button
              type="link"
              onClick={() => changeIsTravelInfo(index)}>
              添加
            </Button>
            <span>|</span>
            <Button
              disabled={item.isFromAslink}
              type="link"
              onClick={() => deletePassengerInfo(index)}>
              删除
            </Button>
          </>))) : <span>
            <Button
              type="link"
              onClick={() => changeIsSave(index)}>
              保存
            </Button>
            <span>|</span>
            <Button
              disabled={item.isRelation}
              type="link"
              onClick={() => deletePassengerInfo(index)}>
              删除
            </Button>
          </span>}
        </div>
      </div>
    </div>
  )
};
// 单个旅客对应的行李信息
const TravelInformation = props => {

  const { form, changeIsTravelInfo, index, CTSelectOpen, ownerType, passengerInfo, item, imageManagemnt } = props;

  // 行李重量验证
  const pkgWeightValidator = useCallback((rule, value, callback, index) => {
    let pkgDetailInfoDtoList = form.getFieldValue('pkgDetailInfoDtoList') || [];
    let allWeight = 0;
    let totalWeight = form.getFieldValue('tktPkgWeight') || 0;
    // for (let item of pkgDetailInfoDtoList) {
    //   allWeight += (item.pkgWeight || 0);
    // }
    passengerInfo.forEach((item, indexNum) => {
      let numReg = /^[0-9]+(\.[0-9]{1,2})?$/;
      if (index === indexNum) {
        if (numReg.test(value)) allWeight += (value * 10000);
      } else {
        if (item.isTravelInfo) {
          allWeight += ((+pkgDetailInfoDtoList[indexNum].pkgWeight || 0) * 10000);
        } else {
          if (item.isRelation) {
            allWeight += ((+item.pkgWeight || 0) * 10000);
          }
        }
      }
    })

    allWeight = (+allWeight / 10000);

    if (allWeight > totalWeight) {
      callback('所有行李重量应小于客票上行李总重量');
    } else {
      setTimeout(() => {
        form.setFieldsValue({
          accidentPkgWeight: allWeight
        });
      }, 0)
      callback();
    }
  }, [passengerInfo, form]);

  return (
    <div className={styles.travelInformationContent}>
      <Button type="link" icon="close" className={styles.closeIcon} onClick={() => changeIsTravelInfo(index)}></Button>
      <div className={styles.formContentAnother}>
        <FormItem label="行李牌号(TN)">
          {form.getFieldDecorator(`pkgDetailInfoDtoList[${index}]._pkgNo`, {
            rules: [],
            initialValue: ''
          })(
            <Input disabled placeholder="请输入" />
          )}
        </FormItem>
        <FormItem label="行李航线(BR)">
          {form.getFieldDecorator(`pkgDetailInfoDtoList[${index}]._pkgSegment`, {
            rules: [],
            initialValue: ''
          })(
            <Input disabled placeholder="请输入" />
          )}
        </FormItem>
        <FormItem label="行李牌上的目的地">
          {form.getFieldDecorator(`pkgDetailInfoDtoList[${index}]._pkgDst`, {
            rules: [],
            initialValue: ''
          })(
            <Input disabled placeholder="请输入" />
          )}
        </FormItem>
      </div>
      <div className={styles.formContentAnother}>
        <FormItem label="行李重量">
          {form.getFieldDecorator(`pkgDetailInfoDtoList[${index}].pkgWeight`, {
            rules: [
              { required: true, message: '请输入行李重量' },
              { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '最多小数点后2位的数字' },
              { validator: (rule, value, callback) => pkgWeightValidator(rule, value, callback, index) }
            ],
            initialValue: ''
          })(
            <InputNumber
              min={0}
              max={Const.inputNumMax}
              step={0.01}
              style={{ width: '100%' }}
              disabled={item.isRelation}
              placeholder="请输入" />
          )}
        </FormItem>
        <FormItem label="行李颜色(CT)">
          {form.getFieldDecorator(`pkgDetailInfoDtoList[${index}].pkgColor`, {
            rules: [
              { required: true, message: '请选择行李颜色' }
            ],
            initialValue: ''
          })(
            <Input
              placeholder="请输入"
              readOnly
              disabled={item.isRelation}
              suffix={
                <Icon type="diff" onClick={() => {
                  if (!item.isRelation) CTSelectOpen(1, index)
                }} />
              } />
          )}
        </FormItem>
        <FormItem label="行李类别(CT)">
          {form.getFieldDecorator(`pkgDetailInfoDtoList[${index}].pkgType`, {
            rules: [
              { required: true, message: '请选择行李类别' }
            ],
            initialValue: ''
          })(
            <Input
              placeholder="请输入"
              readOnly
              disabled={item.isRelation}
              suffix={
                <Icon type="diff" onClick={() => {
                  if (!item.isRelation) CTSelectOpen(2, index)
                }} />
              } />
          )}
        </FormItem>
      </div>
      <div className={styles.formContentAnother}>
        <FormItem label="行李描述">
          {form.getFieldDecorator(`pkgDetailInfoDtoList[${index}].pkgContent`, {
            rules: [],
            initialValue: ''
          })(
            <Input
              placeholder="请输入"
              readOnly
              disabled={item.isRelation}
              suffix={
                <Icon type="diff" onClick={() => {
                  if (!item.isRelation) CTSelectOpen(3, index)
                }} />
              } />
          )}
        </FormItem>
        <FormItem label="行李备注">
          {form.getFieldDecorator(`pkgDetailInfoDtoList[${index}].pkgRemark`, {
            rules: [],
            initialValue: ''
          })(
            <Input placeholder="请输入" disabled={item.isRelation} maxLength={80} />
          )}
        </FormItem>
        <FormItem label="逾重行李票号">
          {form.getFieldDecorator(`pkgDetailInfoDtoList[${index}].overweightTktNo`, {
            rules: [],
            initialValue: ''
          })(
            <Input placeholder="请输入" disabled={item.isRelation} maxLength={20} />
          )}
        </FormItem>
      </div>
      {(ownerType === 1 || ownerType === 7) && <div className={styles.formContentAnother}>
        <FormItem label="破损类型">
          {form.getFieldDecorator(`pkgDetailInfoDtoList[${index}].damageType`, {
            rules: [
              { required: !item.isRelation, message: '请选择破损类型' }
            ],
            initialValue: []
          })(
            <Select
              allowClear
              showSearch
              mode="multiple"
              placeholder="请选择"
              disabled={item.isRelation}
              style={{ width: '100%' }}
            >
              {Const.damageTypeList.map((item) => (
                <Option key={item.value}>{item.label}</Option>
              ))}
            </Select>
          )}
        </FormItem>
        <FormItem label="破损部位">
          {form.getFieldDecorator(`pkgDetailInfoDtoList[${index}].damagePart`, {
            rules: [
              { required: !item.isRelation, message: '请选择破损部位' }
            ],
            initialValue: []
          })(
            <Select
              allowClear
              showSearch
              mode="multiple"
              placeholder="请选择"
              disabled={item.isRelation}
              style={{ width: '100%' }}
            >
              {Const.damagePartList.map((item) => (
                <Option key={item.value}>{item.label}</Option>
              ))}
            </Select>
          )}
        </FormItem>
        <FormItem label="破损程度">
          {form.getFieldDecorator(`pkgDetailInfoDtoList[${index}].damageLevel`, {
            rules: [
              { required: !item.isRelation, message: '请选择破损程度' }
            ],
            initialValue: ''
          })(
            <Select
              allowClear
              showSearch
              placeholder="请选择"
              disabled={item.isRelation}
              style={{ width: '100%' }}
            >
              {Const.damageLevelList.map((item) => (
                <Option key={item.value}>{item.label}</Option>
              ))}
            </Select>
          )}
        </FormItem>
      </div>}
      {ownerType === 6 && <div className={styles.formContentAnother}>
        <FormItem label="缺失物品描述">
          {form.getFieldDecorator(`pkgDetailInfoDtoList[${index}].lossItemsContent`, {
            rules: [
              { required: !item.isRelation, message: '请输入缺失物品描述' }
            ],
            initialValue: ''
          })(
            <Input placeholder="请输入" disabled={item.isRelation} maxLength={40} />
          )}
        </FormItem>
      </div>}
      <div className={styles.formContentAnother}>
        {(ownerType === 1 || ownerType === 7) && <Button type="primary" onClick={() => imageManagemnt(index)}>图片管理</Button>}
      </div>
    </div>
  )
}

class PrivateData {
  static isFirst = true;
  static imgs = [];
  static CTTypeMap = new Map()
    .set(1, 'pkgColor')
    .set(2, 'pkgType')
    .set(3, 'pkgContent');
  static passengerInfoListhaveArr = ['pkgNo', 'pkgSegment', 'pkgDst'];
  static passengerInfoList = ['pkgNo', 'pkgSegment', 'pkgDst', 'pkgWeight', 'pkgColor', 'pkgType', 'pkgContent', 'pkgRemark', 'overweightTktNo', 'damagePart', 'damageLevel', 'damageType', 'lossItemsContent'];
  static dealImgArr = (imgArr = []) => {
    let goodFileListData = imgArr.filter(item => {
      return item.oneType === 1
    });

    let touristFileListData = imgArr.filter(item => {
      return item.oneType === 2
    });

    let paperFileListData = imgArr.filter(item => {
      return item.oneType === 3
    });

    let luggageFileListData = imgArr.filter(item => {
      return item.oneType === 4
    });

    return {
      goodFileList: goodFileListData,
      touristFileList: touristFileListData,
      paperFileList: paperFileListData,
      luggageFileList: luggageFileListData,
    };
  };
  static lostItemPic = {
    goodFileList: [],
    touristFileList: [],
    paperFileList: [],
    luggageFileList: []
  };
}

const Setp2 = props => {

  const { prevStep, nextStep, className, form, ownerType, itemData, type, stepCurrent } = props;

  const [isHaveInfo, setIsHaveInfo] = useState(false);

  const [passengerInfo, setPassengerInfo] = useState([]); // 旅服信息列表

  const [CTSelectVisible, setCTSelectVisible] = useState(false); // 颜色、类别、描述弹窗
  const [CTType, setCTType] = useState(''); // 类型 1color 2category 3desc
  const [CTIndex, setCTIndex] = useState(''); // 索引值
  const [CTVal, setCTVal] = useState(''); // 值

  const [lostItemPicVisible, handleLostItemPicVisible] = useState(false); // PicUpload
  const [lostItemPicManageVisible, handleLostItemPicManageVisible] = useState(false); // ShowPic
  // 是否有图片
  const [lostItemPic, handleLostItemPicture] = useState(PrivateData.lostItemPic);

  const [imgIndex, setImgIndex] = useState('');

  // 获取旅客信息
  const { run: runGetPkgDetailInfo } = useRequest(params => getPkgDetailInfo(params), {
    manual: true,
    onSuccess (res) {
      console.log(res, '获取旅客信息');
      let data = res || [];
      let arr1 = [];
      let arr2 = [];
      // let accidentPkgWeight = 0;
      // let accidentPkgCount = 0;
      for (let item of data) {
        let arrItem1 = {};
        let arrItem2 = {};
        // for (let keyName of PrivateData.passengerInfoList) {
        //   if (keyName === 'pkgWeight') {
        //     arrItem1[keyName] = +item[keyName] || '';
        //     continue;
        //   }
        //   if (keyName === 'damageType' || keyName === 'damagePart') {
        //     arrItem1[keyName] = item[keyName] || [];
        //     continue;
        //   }
        //   arrItem1[keyName] = item[keyName] || '';
        // }
        for (let keyName of PrivateData.passengerInfoListhaveArr) {
          arrItem2[keyName] = item[keyName] || '';
        }
        arr1.push({
          isTravelInfo: false,
          isSave: true,
          isRelation: false,
          isFromAslink: true,
          // ...arrItem1
          ...arrItem2
        })
        arr2.push(arrItem2);
        // accidentPkgWeight += +item.pkgWeight;
        // accidentPkgCount++;
      }
      setPassengerInfo([...arr1]);
      if (data.length >= 1) {
        setIsHaveInfo(true);
        let info = data[0];
        setTimeout(() => {
          form.setFieldsValue({
            tktPkgWeight: info.pkgWeight || 0,
            tktPkgCount: info.pkgCount || 0,
            pkgDetailInfoDtoList: arr2,
            // accidentPkgWeight,
            // accidentPkgCount
          })
        }, 0);
      } else {
        setIsHaveInfo(false);
      }
    }
  });

  const tktPkgCountValidator = useCallback((rule, value, callback) => {
    if (value) {
      if (passengerInfo.length === 0) {
        callback()
      } else {
        let num = 0;
        for (let item of passengerInfo) {
          if (item.isSave) num++;
        }
        if (num > value) {
          message.warning('已添加行李信息超过行李总件数，请删除多余的行李信息或增加行李总件数');
          callback(' ');
        } else {
          callback();
        }
      }
    } else {
      callback('');
    }
  }, [passengerInfo, form]);

  useEffect(() => {
    return () => {
      PrivateData.isFirst = true;
    }
  }, []);

  useEffect(() => {
    if (stepCurrent === 1) {
      if (!PrivateData.isFirst) return;
      PrivateData.isFirst = false;
      if (type === 'add' && itemData.flightNo && itemData.tktNo) {
        runGetPkgDetailInfo({
          flightNo: itemData.flightNo || '',
          tktNo: itemData.tktNo || '',
        });
      }
      if (type === 'edit') {
        let data = itemData.pkgDetailInfoList || [];
        let arr = [];
        let pkgDetailInfoDtoList = [];
        let accidentPkgCount = 0;
        let accidentPkgWeight = 0;
        for (let item of data) {
          let formItem = {};
          for (let keyName of PrivateData.passengerInfoList) {
            if (keyName === 'pkgWeight') {
              formItem[keyName] = +item[keyName] || '';
            } else if (keyName === 'damageType' || keyName === 'damagePart') {
              formItem[keyName] = (item[keyName] ? item[keyName].split(',') : []) || [];
            } else {
              formItem[keyName] = item[keyName] || '';
            }
            item[keyName] = formItem[keyName];
          }
          arr.push({
            isTravelInfo: itemData.pkgNo === item.pkgNo,
            isSave: true,
            isRelation: itemData.pkgNo !== item.pkgNo,
            ...item
          });
          accidentPkgCount++;
          accidentPkgWeight += ((+item.pkgWeight || 0) * 10000);
          formItem['_pkgNo'] = formItem['pkgNo'];
          formItem['_pkgSegment'] = formItem['pkgSegment'];
          formItem['_pkgDst'] = formItem['pkgDst'];
          pkgDetailInfoDtoList.push(formItem);
        }
        setIsHaveInfo(false);
        setPassengerInfo([...arr]);
        setTimeout(() => {
          form.setFieldsValue({
            pkgDetailInfoDtoList: pkgDetailInfoDtoList,
            accidentPkgCount,
            accidentPkgWeight: accidentPkgWeight / 10000
          })
        }, 0);
      }
    }
  }, [itemData, type, stepCurrent]);

  // 颜色、类别、描述弹窗 - 关闭
  const CTSelectClose = useCallback(() => {
    setCTSelectVisible(false);
  }, []);
  // 颜色、类别、描述弹窗 - 打开
  const CTSelectOpen = useCallback((type, index) => {
    let pkgDetailInfoDtoList = form.getFieldValue('pkgDetailInfoDtoList') || [];
    let val = pkgDetailInfoDtoList[index][PrivateData.CTTypeMap.get(type)] || '';
    if (type === 3) {
      if (!val) {
        val = ['', '', ''];
      } else {
        val = val.split(',');
      }
    }
    setCTVal(val);
    setCTIndex(index);
    setCTType(type);
    setCTSelectVisible(true);
  }, []);
  // 颜色、类别、描述弹窗 - 取消
  const CTSelectCancel = useCallback(() => {
    CTSelectClose();
  }, []);
  // 颜色、类别、描述弹窗 - 提交
  const CTSelectSubmit = useCallback(val => {
    let pkgDetailInfoDtoList = form.getFieldValue('pkgDetailInfoDtoList') || [];
    if (CTType === 3) {
      pkgDetailInfoDtoList[CTIndex][PrivateData.CTTypeMap.get(CTType)] = val.join(',');
    } else {
      pkgDetailInfoDtoList[CTIndex][PrivateData.CTTypeMap.get(CTType)] = val;
    }
    form.setFieldsValue({
      pkgDetailInfoDtoList: pkgDetailInfoDtoList
    });
    CTSelectClose();
  }, [CTType, CTIndex]);

  // 旅客行李信息 - 新增
  const addPassengerInfo = useCallback(() => {
    let _passengerInfo = passengerInfo;
    _passengerInfo.push({
      isTravelInfo: false, // 是否已添加
      isSave: false, // 是否保存
      imgs: []
    });
    setPassengerInfo([..._passengerInfo]);
  }, [passengerInfo]);
  // 旅客行李信息 - 删除
  const deletePassengerInfo = useCallback(index => {
    Modal.confirm({
      title: '确认删除',
      content: '确认删除该条行李',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        let pkgDetailInfoDtoList = form.getFieldValue('pkgDetailInfoDtoList') || [];
        let _passengerInfo = passengerInfo;
        _passengerInfo.splice(index, 1);
        pkgDetailInfoDtoList.splice(index, 1);
        form.setFieldsValue({
          pkgDetailInfoDtoList: pkgDetailInfoDtoList
        });
        setPassengerInfo([..._passengerInfo]);
      }
    });
  }, [passengerInfo, form]);
  // 旅客行李信息 - 改变添加已添加状态
  const changeIsTravelInfo = useCallback(index => {
    let _passengerInfo = passengerInfo;
    let pkgDetailInfoDtoList = form.getFieldValue('pkgDetailInfoDtoList') || [];
    let _passengerInfoObj = {
      ..._passengerInfo[index]
    };
    if (!_passengerInfo[index].isTravelInfo) {
      form.validateFields(['tktPkgCount', 'tktPkgWeight'], { force: true }, (err, fieldsValue) => {
        if (err) return;
        _passengerInfo[index].isTravelInfo = true;
        setPassengerInfo([..._passengerInfo]);
        let num = 0;
        let allWeight = 0;
        _passengerInfo.forEach((item, indexNum) => {
          if (item.isTravelInfo || item.isRelation) num++;
          if (item.isTravelInfo) {
            if (index === indexNum) {
              allWeight += ((+_passengerInfo[indexNum].pkgWeight || 0) * 10000);
            } else {
              allWeight += ((+pkgDetailInfoDtoList[indexNum].pkgWeight || 0) * 10000);
            }
          } else {
            if (item.isRelation) {
              allWeight += ((+item.pkgWeight || 0) * 10000);
            }
          }
        });
        for (let keyName of PrivateData.passengerInfoList) {
          // if (!_passengerInfo[index].isRelation && (PrivateData.passengerInfoListhaveArr.indexOf(keyName) > -1)) {
          //   continue;
          // }
          if (PrivateData.passengerInfoListhaveArr.indexOf(keyName) > -1) {
            continue;
          }
          if (keyName === 'pkgWeight') {
            pkgDetailInfoDtoList[index][keyName] = +_passengerInfoObj[keyName] || '';
            continue;
          }
          if (keyName === 'damageType' || keyName === 'damagePart') {
            pkgDetailInfoDtoList[index][keyName] = _passengerInfoObj[keyName] || [];
            continue;
          }
          pkgDetailInfoDtoList[index][keyName] = _passengerInfoObj[keyName] || '';
        }
        pkgDetailInfoDtoList[index]['_pkgNo'] = pkgDetailInfoDtoList[index]['pkgNo'];
        pkgDetailInfoDtoList[index]['_pkgSegment'] = pkgDetailInfoDtoList[index]['pkgSegment'];
        pkgDetailInfoDtoList[index]['_pkgDst'] = pkgDetailInfoDtoList[index]['pkgDst'];
        setTimeout(() => {
          form.setFieldsValue({
            accidentPkgCount: num,
            accidentPkgWeight: allWeight / 10000,
            pkgDetailInfoDtoList: pkgDetailInfoDtoList
          });
        }, 0)
      })
    } else {
      _passengerInfo[index] = {
        ..._passengerInfo[index],
        ...pkgDetailInfoDtoList[index],
        isTravelInfo: false
      }
      setPassengerInfo([..._passengerInfo]);
      let num = 0;
      let allWeight = 0;
      _passengerInfo.forEach((item, indexNum) => {
        if (item.isTravelInfo || item.isRelation) num++;
        if (item.isTravelInfo) {
          if (index === indexNum) {
            allWeight += ((+_passengerInfo[indexNum].pkgWeight || 0) * 10000);
          } else {
            allWeight += ((+pkgDetailInfoDtoList[indexNum].pkgWeight || 0) * 10000);
          }
        } else {
          if (item.isRelation) {
            allWeight += ((+item.pkgWeight || 0) * 10000);
          }
        }
      });
      form.setFieldsValue({
        accidentPkgCount: num,
        accidentPkgWeight: allWeight / 10000
      });
    }
  }, [passengerInfo, form]);
  // 旅客行李信息 - 改变保存编辑状态
  const changeIsSave = useCallback(index => {
    form.validateFields([`pkgDetailInfoDtoList[${index}]`], (err, fieldsValue) => {
      if (err) return;
      let _passengerInfo = passengerInfo;
      _passengerInfo[index].isSave = !_passengerInfo[index].isSave;
      setPassengerInfo([..._passengerInfo]);
    })
  }, [passengerInfo, form]);

  // 图片管理
  const imageManagemnt = useCallback((index) => {
    setImgIndex(index);
    let _lostItemPic = PrivateData.dealImgArr(passengerInfo[index].imgs || []);
    handleLostItemPicture(_lostItemPic);
    // if (type === 'add') {
    //   handleLostItemPicVisible(true);
    // } else {
    //   handleLostItemPicManageVisible(true);
    // }
    handleLostItemPicManageVisible(true);
  }, [passengerInfo, type]);

  // 新增图片、改变图片
  const handleImgs = async fields => {

    let img = []
    let obj = {};

    for (let category in fields) {
      fields[category].forEach(imgInfo => {
        imgInfo.relevance = itemData['accidentId'] || ''
        img.push(imgInfo)
      })
    }

    img = img.filter(item => {
      return !(!item.id && item.remark === 1)
    })

    let _passengerInfo = passengerInfo;
    _passengerInfo[imgIndex].imgs = [...img];
    setPassengerInfo(_passengerInfo);

    // PrivateData.imgs = [...img];
    handleLostItemPicVisible(false);
    handleLostItemPicManageVisible(false);
  };

  // 下一步
  const step2NextStep = useCallback(() => {
    form.validateFields({ force: true }, (err, fieldsValue) => {
      if (err) return;
      let isFinish = false;
      for (let item of passengerInfo) {
        if (item.isTravelInfo && !item.isRelation) {
          isFinish = true;
          break;
        }
      }
      if (isFinish) {
        let pkgDetailInfoDtoList = [];
        passengerInfo.forEach((item, index) => {
          if (item.isTravelInfo && !item.isRelation) {
            if (item.id) {
              fieldsValue.pkgDetailInfoDtoList[index]['accidentId'] = itemData['accidentId'];
            }
            let saveItem = fieldsValue.pkgDetailInfoDtoList[index];
            saveItem.imgs = item.imgs || [];
            pkgDetailInfoDtoList.push(saveItem);
          }
        });
        fieldsValue.pkgDetailInfoDtoList = pkgDetailInfoDtoList;
        fieldsValue.pkgDetailInfoDtoList.forEach((item, index) => {
          if (item.damagePart && item.damagePart.length !== 0) {
            fieldsValue.pkgDetailInfoDtoList[index].damagePart = item.damagePart.join(',');
          } else {
            fieldsValue.pkgDetailInfoDtoList[index].damagePart = '';
          }
          if (item.damageType && item.damageType.length !== 0) {
            fieldsValue.pkgDetailInfoDtoList[index].damageType = item.damageType.join(',');
          } else {
            fieldsValue.pkgDetailInfoDtoList[index].damageType = '';
          }
        })
        console.log(fieldsValue, 'fieldsValue');
        nextStep(fieldsValue);
      } else {
        message.warning('请完善行李信息');
      }
    })
  }, [form, itemData, passengerInfo]);

  return (
    <div className={`${styles.stepWrapper} ${className}`}>
      <div className={styles.stepContentAnother}>
        <Collapse activeKey={['1']} style={{ width: '30%' }}>
          <Panel showArrow={false} header="旅客行李信息" key="1">
            {passengerInfo.map((item, index) => (
              <PassengerInfoItem
                item={item}
                index={index}
                key={index}
                form={form}
                passengerInfo={passengerInfo}
                deletePassengerInfo={deletePassengerInfo}
                changeIsSave={changeIsSave}
                changeIsTravelInfo={changeIsTravelInfo}>
              </PassengerInfoItem>
            ))}
            <Button
              type="dashed"
              icon="plus"
              disabled={!form.getFieldValue('tktPkgCount') || passengerInfo.length >= form.getFieldValue('tktPkgCount')}
              onClick={() => addPassengerInfo()}
              style={{ width: '100%', marginTop: '20px' }}>
              新增行李
            </Button>
          </Panel>
        </Collapse>
        <Collapse activeKey={['1']} style={{ width: '65%' }}>
          <Panel showArrow={false} header="异常行李信息" key="1">
            <div className={styles.formContentAnother}>
              <FormItem label="客票上行李总件数">
                {form.getFieldDecorator('tktPkgCount', {
                  rules: [
                    { required: true, message: '请输入客票上行李总件数' },
                    { pattern: /^[1-9][0-9]?$/, message: '请输入0-99的整数' },
                    { validator: tktPkgCountValidator }
                  ],
                  initialValue: itemData.tktPkgCount || ''
                })(
                  <InputNumber
                    placeholder="请输入"
                    disabled={isHaveInfo}
                    min={1}
                    step={1}
                    max={99}
                    style={{ width: '100%' }} />
                )}
              </FormItem>
              <FormItem label="客票上行李总重量">
                {form.getFieldDecorator('tktPkgWeight', {
                  rules: [
                    { required: true, message: '请输入客票上行李总重量' },
                    { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '最多小数点后2位的数字' },
                  ],
                  initialValue: itemData.tktPkgWeight || ''
                })(
                  <InputNumber
                    step={0.01}
                    placeholder="请输入"
                    disabled={isHaveInfo}
                    min={0}
                    max={Const.inputNumMax}
                    style={{ width: '100%' }} />
                )}
              </FormItem>
              <FormItem label="超重行李重量">
                {form.getFieldDecorator('pkgOverWeight', {
                  rules: [
                    { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '最多小数点后2位的数字' },
                  ],
                  initialValue: itemData.pkgOverWeight || ''
                })(
                  <InputNumber
                    step={0.01}
                    placeholder="请输入"
                    min={0}
                    max={Const.inputNumMax}
                    style={{ width: '100%' }} />
                )}
              </FormItem>
            </div>
            <div className={styles.formContentAnother}>
              <FormItem label="发生事故行李件数">
                {form.getFieldDecorator('accidentPkgCount', {
                  rules: [
                    { required: true, message: '请输入发生事故行李件数' }
                  ],
                  initialValue: itemData.accidentPkgCount || ''
                })(
                  <InputNumber
                    disabled
                    placeholder="请输入"
                    min={0}
                    max={Const.inputNumMax}
                    style={{ width: '100%' }} />
                )}
              </FormItem>
              <FormItem label="发生事故行李总重量">
                {form.getFieldDecorator('accidentPkgWeight', {
                  rules: [
                    { required: true, message: '请输入发生事故行李总重量' },
                    { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '最多小数点后2位的数字' },
                  ],
                  initialValue: itemData.accidentPkgWeight || ''
                })(
                  <InputNumber
                    step={0.01}
                    disabled
                    placeholder="请输入"
                    min={0}
                    max={Const.inputNumMax}
                    style={{ width: '100%' }} />
                )}
              </FormItem>
              <FormItem label="超重行李费用">
                {form.getFieldDecorator('pkgOverWeightPrice', {
                  rules: [
                    { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '最多小数点后2位的数字' },
                  ],
                  initialValue: itemData.pkgOverWeightPrice || ''
                })(
                  <InputNumber
                    step={0.01}
                    placeholder="请输入"
                    min={0}
                    max={Const.inputNumMax}
                    style={{ width: '100%' }} />
                )}
              </FormItem>
            </div>
            {passengerInfo.map((item, index) => {
              if (item.isTravelInfo) {
                return <TravelInformation
                  key={index}
                  index={index}
                  form={form}
                  item={item}
                  passengerInfo={passengerInfo}
                  changeIsTravelInfo={changeIsTravelInfo}
                  CTSelectOpen={CTSelectOpen}
                  imageManagemnt={imageManagemnt}
                  ownerType={ownerType}>
                </TravelInformation>
              }
            })}
          </Panel>
        </Collapse>
      </div>
      <div className={styles.btnBox}>
        <Button onClick={prevStep} style={{ marginRight: '10px' }}>上一步</Button>
        <Button type="primary" onClick={() => step2NextStep()}>下一步</Button>
      </div>

      <CTSelect
        modalVisible={CTSelectVisible}
        onCancel={CTSelectCancel}
        onSubmit={CTSelectSubmit}
        CTType={CTType}
        CTVal={CTVal}
      ></CTSelect>
      {lostItemPicVisible && <PicUpload
        onSubmit={async value => {
          handleLostItemPicture(value)
          const success = await handleImgs(value)
        }}
        onCancel={() => handleLostItemPicVisible(false)}
        lostItemPicVisible={lostItemPicVisible}
        lostItemPic={lostItemPic}
        ownerType={ownerType}
      ></PicUpload>}
      {lostItemPicManageVisible && <ShowPic
        onSubmit={async value => {
          handleLostItemPicture(value)
          const success = await handleImgs(value)
        }}
        toUpload={(value) => {
          handleLostItemPicture(value)
          handleLostItemPicManageVisible(false)
          handleLostItemPicVisible(true)
        }}
        onCancel={() => handleLostItemPicManageVisible(false)}
        lostItemPicManageVisible={lostItemPicManageVisible}
        lostItemPic={lostItemPic}
        ownerType={ownerType}
        status={type === 'add' ? '0' : itemData.status}
      ></ShowPic>}
    </div>
  )
}

export default Form.create()(Setp2);
